<template>
  <div id="app">
    <div class="content-header">
      <h1>后台管理<small>收银台列表</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>后台管理</el-breadcrumb-item>
        <el-breadcrumb-item>收银台列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="app-container">
      <div class="box">
        <div class="filter-container">
          <el-input placeholder="请输入收银台号" v-model="pagination.queryString" style="width: 200px;"
                    class="filter-item" clearable @clear="findPage"></el-input>
          <el-button @click="findPage()" icon="el-icon-search" class="dalfBut">查询收银台号</el-button>
          <el-button type="primary" class="butT" @click="handleCreate()">添加收银台</el-button>
        </div>
        <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
          <!---->
          <el-table-column type="index" align="center" label="#"></el-table-column>
          <el-table-column prop="cashierId" label="收银台号" align="center"></el-table-column>
          <el-table-column prop="startTime" label="开始工作时间" align="center"></el-table-column>
          <el-table-column prop="endTime" label="结束工作时间" align="center"></el-table-column>
          <el-table-column prop="cashierAmmount" label="台内金额" align="center"></el-table-column>
          <el-table-column label="管理" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            class="pagiantion"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[2,5,10,15]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>

        <!-- 新增标签弹层 手机号 真实姓名（*） 密码 备注 角色-->
        <div class="add-form">
          <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
            <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right"
                     label-width="100px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="formData.mobile"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="formData.realName"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="formData.username"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="密码">
                    <el-input v-model="formData.password"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleAdd()">确定</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 编辑标签弹层 手机号 真实姓名（*） 密码 备注 角色-->
        <div class="edit-form">
          <el-dialog title="编辑用户" :visible.sync="dialogFormVisible4Edit">
            <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right"
                     label-width="100px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="formData.mobile"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="formData.realName"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="昵称" prop="username">
                    <el-input v-model="formData.username"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
              <el-button type="primary" @click="handleEdit()">确定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      password: '',
      pagination: { // 分页相关模型数据
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页显示的记录数
        total: 0, // 总记录数
        queryString: null, // 查询条件
        datetimepicker: []
      },
      dataList: [], // 当前页要展示的分页列表数据
      roleList: [], // 下拉框显示的所有角色
      formData: {}, // 表单数据
      dialogFormVisible: false, // 增加表单是否可见
      dialogFormVisible4Edit: false, // 编辑表单是否可见
      rules: { // 校验规则
        // 真实姓名
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // 钩子函数，VUE对象初始化完成后自动执行
  created () {
    // this.findPage() // VUE对象初始化完成后调用分页查询方法，完成分页查询
    this.getRole()
  },
  methods: {
    async getRole () {
      const rid = window.sessionStorage.getItem('rid')
      // eslint-disable-next-line eqeqeq
      if (rid == 1 || rid == 2 || rid == 3) {
        await this.findPage()
      }
    },
    // 监听 switch 开关状态的改变
    async userStateChanged (goodsinfo) {
      console.log(goodsinfo)
      const { data: res } = await this.$http.put(
        `/server/goods/${goodsinfo.cid}/state/${goodsinfo.onSale}`
      )
      if (res.flag !== true) {
        goodsinfo.onSale = !goodsinfo.onSale
        return this.$message.error('更新商品可售状态失败！')
      }
      this.$message.success('更新商品可售状态成功！')
    },
    // 编辑
    handleEdit () {
      // 进行表单校验
      this.$refs.dataEditForm.validate((valid) => {
        if (valid) {
          // 表单校验通过，可以提交数据
          this.$http.post('/user/updateUser.do', this.formData).then((res) => {
            if (res.data.flag) {
              // 弹出成功提示信息
              this.$message({
                type: 'success',
                message: res.data.message
              })
            } else {
              // 执行失败
              this.$message.error(res.data.message)
            }
          }).finally(() => {
            // 不管成功还是失败，都调用分页查询方法
            this.findPage()
            // 隐藏编辑窗口
            this.dialogFormVisible4Edit = false
          })
        } else {
          // 表单校验不通过
          this.$message.error('表单数据校验失败!')
          return false
        }
      })
    },
    // 添加按钮
    handleAdd () {
      // 进行表单校验
      this.$refs.dataAddForm.validate((valid) => {
        if (valid) {
          // 表单校验通过，发ajax请求，把数据录入至后台处理
          this.$http.post('/user/add.do', this.formData).then((res) => {
            // 关闭新增窗口
            this.dialogFormVisible = false
            if (res.data.flag) {
              // 新增成功后，重新调用分页查询方法，查询出最新的数据
              this.findPage()
              // 弹出提示信息
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            } else { // 执行失败
              this.$message.error('添加失败')
            }
          })
        } else { // 校验不通过
          this.$message.error('校验失败，请检查输入格式')
          return false
        }
      })
    },
    // 分页查询
    async findPage () {
      // 发送ajax，提交分页请求（页码，每页显示条数，查询条件)
      const param = {
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        queryString: this.pagination.queryString,
        datetimepicker: this.pagination.datetimepicker
      }
      var param2 = this.$encruption(JSON.stringify(param))
      const { data: res } = await this.$http.post('/server/manage/cashier/findPage.do', param2)
      // 解析controller响应回的数据
      if (!res.flag) {
        return this.$message.error('获取仓库列表失败！')
      }
      this.pagination.total = res.data.total
      this.dataList = res.data.records
    },
    // 下拉框获取所有角色
    getRole_name () {
      this.$http.get('/role/getRole_name.do').then((res) => {
        // 解析响应回的数据
        this.roleList = res.data.records
      })
    },
    // 重置表单
    resetForm () {
      this.formData = {}// 重置表格数据
      this.$refs.dataAddForm.resetFields()
    },
    // 弹出添加窗口
    handleCreate () {
      this.dialogFormVisible = true
      this.resetForm()
    },
    // 弹出编辑窗口
    handleUpdate (row) {
      // 弹出
      this.dialogFormVisible4Edit = true
      this.formData = row
      this.$refs.dataEditForm.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          'users/' + this.formData.id,
          {
            realName: this.formData.realName,
            mobile: this.formData.mobile,
            username: this.formData.username
          }
        )

        if (res.flag !== true) {
          return this.$message.error('更新用户信息失败！')
        }

        // 关闭对话框
        this.dialogFormVisible4Edit = false
        // 刷新数据列表
        this.findPage()
        // 提示修改成功
        this.$message.success('更新用户信息成功！')
      })
      // 回显数据，发送ajax请求根据ID查询当前检查项数据
      // axios.get("/user/updateUser.do?id=" + row.id).then((res) => {
      //     if (res.data.flag) {
      //         //进行回显，基于VUE的数据绑定实现
      //         this.formData = res.data.data;
      //     } else {
      //         //查询失败，弹出提示
      //         this.$message.error(res.data.message);
      //     }
      // });
    },
    // 切换页码
    handleCurrentChange (currentPage) {
      // 设置最新的页码
      this.pagination.currentPage = currentPage
      // 重新调用findPage方法进行分页查询
      this.findPage()
    },
    handleSizeChange (newSize) {
      this.pagination.pageSize = newSize
      this.findPage()
    },
    async handleDelete (row) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('/user/deleteById.do?id=' + row.id)

      if (res.flag) {
        this.$message.success('删除用户成功！')
        this.findPage()
      } else {
        return this.$message.error('删除用户失败！')
      }
    },
    handleForbidden (row) {
      this.$confirm('你确定要禁用当前用户吗？', '提示', { // 确认框
        type: 'warning'
      }).then(() => {
        // 用户点击确定按钮，发送ajax请求，将检查项ID提交到Controller进行处理
        this.$http.get('/user/forbid.do?id=' + row.id).then((res) => {
          if (res.data.flag) {
            // 执行成功
            // 弹出成功提示信息
            this.$message({
              type: 'success',
              message: res.data.message
            })
            // 重新进行分页查询
            this.findPage()
          } else {
            // 执行失败
            this.$message.error(res.data.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
  @import "../../assets/css/style.css";
</style>
